<script setup lang="ts">
import type { InfoItem } from '@/components/DetailCard.vue'
import { onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'

// 定义页面配置
definePage({
  style: {
    navigationBarTitleText: '运单详情',
    enablePullDownRefresh: true,
  },
})

// 使用流程相关功能
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading } = useFlow()

// 业务详情数据
const businessData = ref<any>(null)
const errorMessage = ref('')
const flowIdValue = ref<string>('')
const idValue = ref<string>('')

// 基础信息卡片
const basicInfo = ref<InfoItem[]>([
  {
    label: '审批标题',
    key: 'title',
    value: '运单制作审批',
    slot: 'title',
  },
  {
    label: '运单号',
    key: 'shipNo',
    value: '',
    type: 'default',
  },
  {
    label: '创建时间',
    key: 'createTime',
    value: '',
    type: 'datetime',
  },
  {
    label: '更新时间',
    key: 'updateTime',
    value: '',
    type: 'datetime',
  },
  {
    label: '申请人',
    key: 'applicant',
    value: '',
  },
  {
    label: '申请部门',
    key: 'department',
    value: '',
  },
])

// 运单相关信息卡片
const shippingInfo = ref<InfoItem[]>([
  {
    label: '起运地',
    key: 'origin',
    value: '',
  },
  {
    label: '目的地',
    key: 'destination',
    value: '',
  },
  {
    label: '货物类型',
    key: 'cargoType',
    value: '',
  },
  {
    label: '货物重量',
    key: 'weight',
    value: '',
    type: 'currency',
  },
  {
    label: '货物体积',
    key: 'volume',
    value: '',
  },
  {
    label: '运输方式',
    key: 'transportType',
    value: '',
  },
  {
    label: '预计到达时间',
    key: 'expectedArrival',
    value: '',
    type: 'datetime',
  },
  {
    label: '特殊要求',
    key: 'specialRequirements',
    value: '',
    forceMultiline: true,
  },
])

// 流程信息卡片
const processInfo = ref<InfoItem[]>([
  {
    label: '流程实例ID',
    key: 'processId',
    value: '',
    slot: 'processId',
  },
  {
    label: '流程名称',
    key: 'processName',
    value: '',
  },
  {
    label: '当前环节',
    key: 'currentStep',
    value: '',
    type: 'status',
  },
  {
    label: '流程状态',
    key: 'processStatus',
    value: '',
    type: 'status',
  },
  {
    label: '审批人',
    key: 'approver',
    value: '',
  },
  {
    label: '审批时间',
    key: 'approveTime',
    value: '',
    type: 'datetime',
  },
  {
    label: '审批意见',
    key: 'approveComment',
    value: '',
    forceMultiline: true,
  },
])

// 获取业务详情数据
async function getBusinessData() {
  try {
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }
    // 这里模拟数据，实际项目中需要调用具体的业务接口
    const mockData = {
      title: '运单制作审批',
      shipNo: `SH${Date.now()}`,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      applicant: '张三',
      department: '物流部',
      origin: '北京市朝阳区',
      destination: '上海市浦东新区',
      cargoType: '电子产品',
      weight: 1500.50,
      volume: '10.5m³',
      transportType: '公路运输',
      expectedArrival: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString(),
      specialRequirements: '需要防震包装，运输过程中请保持平稳行驶',
      currentStep: '部门审批',
      processStatus: 'pending',
      approver: '',
      approveTime: '',
      approveComment: '',
    }

    // 更新基础信息
    basicInfo.value = basicInfo.value.map(item => ({
      ...item,
      value: mockData[item.key as keyof typeof mockData] || '',
    }))

    // 更新运单信息
    shippingInfo.value = shippingInfo.value.map(item => ({
      ...item,
      value: mockData[item.key as keyof typeof mockData] || '',
    }))

    // 更新流程信息
    processInfo.value = processInfo.value.map(item => ({
      ...item,
      value: mockData[item.key as keyof typeof mockData] || '',
    }))

    businessData.value = mockData
  }
  catch (error) {
    console.error('获取业务详情失败:', error)
    errorMessage.value = '获取业务详情失败，请重试'
  }
}

// 更新流程信息
function updateProcessInfo() {
  if (currentProcess.value) {
    processInfo.value = processInfo.value.map((item) => {
      switch (item.key) {
        case 'processId':
          return { ...item, value: currentProcess.value?.id || '' }
        case 'processName':
          return { ...item, value: currentProcess.value?.name || '' }
        case 'currentStep':
          // currentProcess没有currentActivity属性，使用name作为当前环节
          return { ...item, value: currentProcess.value?.name || '' }
        case 'processStatus':
          return { ...item, value: currentProcess.value?.status || '' }
        case 'approver':
          return { ...item, value: currentProcess.value?.startUser?.nickname || '' }
        case 'approveTime':
          return { ...item, value: currentProcess.value?.endTime || '' }
        case 'approveComment':
          return { ...item, value: currentProcess.value?.formVariables?.comment || '' }
        default:
          return item
      }
    })
  }
}

// 页面加载时获取数据
onLoad(async (e: any) => {
  if (e.flowId) {
    flowIdValue.value = e.flowId
  }
  idValue.value = e.id || ''
  if (!e.id) {
    uni.showToast({
      title: '没有获取到id',
      icon: 'none',
    })
    return
  }
  await Promise.all([
    getProcessInstance(idValue.value),
    getBusinessData(),
  ])
  updateProcessInfo()
})

// 页面显示时重新获取数据
onShow(async () => {
  if (idValue.value) {
    await Promise.all([
      getProcessInstance(idValue.value),
      getBusinessData(),
    ])
    updateProcessInfo()
  }
})
</script>

<template>
  <view class="page">
    <!-- 审批状态卡片 -->
    <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />

    <!-- 错误信息显示 -->
    <view v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </view>

    <!-- 基础信息卡片 -->
    <DetailCard
      title="基础信息"
      :info-list="basicInfo"
    >
      <!-- 自定义标题插槽 -->
      <template #title="{ item }">
        <view class="custom-title">
          <text>{{ item.value }}</text>
        </view>
      </template>
    </DetailCard>

    <!-- 运单信息卡片 -->
    <DetailCard
      title="运单信息"
      :info-list="shippingInfo"
      :show-divider="true"
    />

    <!-- 流程信息卡片 -->
    <DetailCard
      title="流程信息"
      :info-list="processInfo"
    >
      <!-- 自定义流程ID插槽 -->
      <template #processId="{ item }">
        <view class="process-id">
          <text>{{ item.value || '-' }}</text>
        </view>
      </template>
    </DetailCard>

    <!-- 审批操作栏 -->
    <view class="approval-bar">
      <ApprovalActionBar
        v-if="flowIdValue && currentProcess?.status === 1"
        :process-id="flowIdValue"
      />
    </view>
  </view>
</template>

<style scoped>
.page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.error-message {
  background-color: #fff2f0;
  border: 1rpx solid #ffccc7;
  color: #a8071a;
  padding: 20rpx;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.approval-bar {
  margin-top: 20rpx;
}

.custom-title {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.process-id {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

/* 响应式调整 */
@media (max-width: 750rpx) {
  .page {
    padding: 16rpx;
  }
}
</style>
